package org.domain.acount.session;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.domain.acount.entity.Conta;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.framework.EntityQuery;
import org.richfaces.component.state.TreeState;

@Name("contaList")
public class ContaList extends EntityQuery<Conta> {

	@In EntityManager entityManager;
	
	private static final String EJBQL = "select conta from Conta conta";

	private static final String[] RESTRICTIONS = {
			"lower(conta.nome) like lower(concat(#{contaList.conta.nome},'%'))",
			"lower(conta.descricao) like lower(concat(#{contaList.conta.descricao},'%'))", };

	private Conta conta = new Conta();

	public ContaList() {
		setEjbql(EJBQL);
		setRestrictionExpressionStrings(Arrays.asList(RESTRICTIONS));
		setMaxResults(25);
	}

	public Conta getConta() {
		return conta;
	}
	
	@SuppressWarnings("unchecked")
	public List<Conta> autoComplete(Object o) {
		String sql =  this.getEjbql() + " where conta.idConta != 0 and lower(conta.nome) like concat('%',lower('"+o.toString()+"'),'%')";
		List<Conta> resultList = this.getEntityManager().createQuery(sql).getResultList();
	   	Query query;
	   	String nomeConta;
	   		for (Iterator<Conta> iterator = resultList.iterator(); iterator.hasNext();) {
	   			Conta contaIterator = iterator.next();
	   			nomeConta = contaIterator.getNome();
	   			// faz loop da conta até chegar na conta pai 0
	   			Conta contaPais = contaIterator;
	   			while (contaPais.getContaIdConta() != 0) {
	   				query = entityManager.createNativeQuery("SELECT * FROM conta WHERE id_conta = ? order by nome", Conta.class);
	   				query.setParameter(1, contaPais.getContaIdConta());
	   				contaPais = (Conta) query.getSingleResult();
	   				nomeConta = contaPais.getNome() + " - " + nomeConta;
		   			contaIterator.setNomeCheio(nomeConta);
	   			}
	   		}
	   		return resultList;   
	}
	
    
	private List<Conta> arvore;	
	
	public List<Conta> getArvore() {
		if (arvore == null) {
			loadDadosTree();
		}
		return arvore;
		
	}
	
	public void setArvore(List<Conta> arvore) {
		this.arvore = arvore;
	}

	 private void loadDadosTree() {
		 	arvore = new ArrayList<Conta>();
		   	Query query = entityManager.createNativeQuery("SELECT * FROM conta WHERE conta_id_conta = 0 AND id_conta > 0 order by nome", Conta.class);
	    	List<Conta> contas = query.getResultList();
	    	for (Iterator<Conta> iterator = contas.iterator(); iterator.hasNext();) {
				Conta conta = iterator.next();
				buscaFilhos(conta);
				arvore.add(conta);
			}
	}
	 
	 private void buscaFilhos(Conta conta) {
		   	Query query = entityManager.createNativeQuery("SELECT * FROM conta WHERE conta_id_conta = ? order by nome", Conta.class);
		   	query.setParameter(1, conta.getIdConta());
	    	List<Conta> contas = query.getResultList();
	    	conta.setFilhos(contas);
	    	for (Iterator<Conta> iterator = contas.iterator(); iterator.hasNext();) {
	    		Conta conta2 = iterator.next();
				buscaFilhos(conta2);
			}
	}	 
	 
	    private Map<Integer, TreeState> treeStateMap = new HashMap<Integer, TreeState>();
	    
	    public TreeState getTreeState(Integer key)
	    {
	        TreeState treeState = treeStateMap.get(key); 
	        if (treeState == null)
	        {
	            treeState = new TreeState();
	            treeStateMap.put(key, treeState);
	        }
	        
	        return treeState;
	    }
	    
	    public void setTreeState(Integer key, TreeState treeState)
	    {
	        treeStateMap.put(key, treeState);
	    }
 
	 
	 
	 
}
